package com.xmy.cultivate.controller;





import com.aliyun.sts20150401.Client;
import com.aliyun.sts20150401.models.AssumeRoleRequest;
import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;



import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("/api/aliApi")
public class AliApiController {

    @Value("${aliyun.vodsss.accessKeyId}")
    String accessKeyId;

    @Value("${aliyun.vodsss.accessKeySecret}")
    String accessKeySecret;

    @Value("${aliyun.vodsss.roleArn}")
    String roleArn;



    @GetMapping("/getStsTokenForVod")
    public Result getStsTokenForVod(){
        // 从环境变量中获取步骤一生成的RAM用户的访问密钥（AccessKey ID和AccessKey Secret）。
        //String accessKeyId = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
        //String accessKeySecret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
        // AssumeRole API 请求参数：RoleArn, RoleSessionName, Policy, and DurationSeconds
        // RoleArn需要通过步骤三在RAM控制台上获取
        //String roleArn = "<role-arn>";
        // RoleSessionName 角色会话名称，自定义参数
        String roleSessionName = "vodsts";
        // 定制你的policy
        String policy = "{\n" +
                "  \"Version\": \"1\",\n" +
                "  \"Statement\": [\n" +
                "    {\n" +
                "      \"Action\": \"vod:*\",\n" +
                "      \"Resource\": \"*\",\n" +
                "      \"Effect\": \"Allow\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        try {
            AssumeRoleResponse response  = assumeRole(accessKeyId, accessKeySecret, roleArn, roleSessionName, policy);
            //System.out.println("Expiration: " + response.getBody().getCredentials().getExpiration());
            //System.out.println("Access Key Id: " + response.getBody().getCredentials().getAccessKeyId());
            //System.out.println("Access Key Secret: " + response.getBody().getCredentials().getAccessKeySecret());
            //System.out.println("Security Token: " + response.getBody().getCredentials().getSecurityToken());
            //System.out.println("RequestId: " + response.getBody().getRequestId());
            Map<String,Object> map = new HashMap<>();
            map.put("ExpirationDateTime",response.getBody().getCredentials().getExpiration());
            map.put("AccessKeyId",response.getBody().getCredentials().getAccessKeyId());
            map.put("AccessKeySecret",response.getBody().getCredentials().getAccessKeySecret());
            map.put("SecurityToken",response.getBody().getCredentials().getSecurityToken());
            map.put("RequestId",response.getBody().getRequestId());

            return new Result(Code.OK,map,"");
        } catch (Exception e) {
            //throw new RuntimeException(e);
            return new Result(Code.ERROR,"",e.getMessage());
        }
    }


/*
    @GetMapping("/getVideoInfo")
    public Result getVideoInfo(@RequestParam(value = "region",defaultValue = "cn-shenzhen",required = false) String region,
                               @RequestParam("videoId") String videoId
                               ) throws ExecutionException, InterruptedException {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Please ensure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are set.
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                //.securityToken(stsToken) // use STS token
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-shenzhen") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // Endpoint 请参考 https://api.aliyun.com/product/vod
                                .setEndpointOverride("vod.cn-shenzhen.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        GetPlayInfoRequest getPlayInfoRequest = GetPlayInfoRequest.builder()
                .videoId(videoId)
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<GetPlayInfoResponse> response = client.getPlayInfo(getPlayInfoRequest);
        // Synchronously get the return value of the API request
        GetPlayInfoResponse resp = response.get();
        String coverUrl = "";
        if (resp.getStatusCode().equals(200)){
            coverUrl = resp.getBody().getVideoBase().getCoverURL();
        }else {

        }
        //resp.getBody().
        //System.out.println(new Gson().toJson(resp));
        // Asynchronous processing of return values
        */
/*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*//*


        // Finally, close the client
        client.close();
        Map<String,Object> map = new HashMap<>();
        map.put("coverUrl",coverUrl);
        return new Result(Code.OK,map,"");
    }
*/


    public static AssumeRoleResponse assumeRole(String accessKeyId, String accessKeySecret, String roleArn, String roleSessionName, String policy) throws Exception {
        Config config = new Config()
                // 从环境变量中获取AccessKey ID的值
                .setAccessKeyId(accessKeyId)
                // 从环境变量中获取AccessKey Secret的值
                .setAccessKeySecret(accessKeySecret);
        config.endpoint = "sts.cn-hangzhou.aliyuncs.com";
        Client client = new Client(config);
        AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
                .setRoleArn(roleArn)
                .setRoleSessionName(roleSessionName)
                .setPolicy(policy);
        RuntimeOptions runtime = new RuntimeOptions();
        return client.assumeRoleWithOptions(assumeRoleRequest, runtime);
    }
}
